package cn.jw.starter.common.current;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;

import io.netty.util.concurrent.DefaultEventExecutor;
import io.netty.util.concurrent.EventExecutor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author 王广帅
 * @version 1.0.0
 * @since 2025/11/22 18:15
 */
@Slf4j
public class JwEventExecutorGroup {

    private EventExecutor[] executorEvents;

    public JwEventExecutorGroup(int threadCount, String name) {
        if (threadCount <= 0) {
            throw new IllegalArgumentException("线程数最少为1");
        }
        executorEvents = new EventExecutor[threadCount];
        for (int i = 0; i < threadCount; i++) {
            executorEvents[i] = new DefaultEventExecutor(new JwThreadFactory(name));
        }
    }

    private EventExecutor select(String key) {
        if (StringUtils.isEmpty(key)) {
            throw new IllegalArgumentException("任务的Key不能为空");
        }
        int hashCode = Math.abs(key.hashCode());
        int index = hashCode % executorEvents.length;
        return executorEvents[index];
    }

    public void execute(String taskName, String key, Runnable task) {
        Map<String, String> copyOfContextMap = MDC.getCopyOfContextMap();
        EventExecutor executor = this.select(key);
        executor.execute(() -> {
            long startTime = System.currentTimeMillis();
            MDC.setContextMap(copyOfContextMap);
            try {
                task.run();
            } catch (Throwable e) {
                log.error("执行任务[{}]异常", taskName, e);
            }
            long endTime = System.currentTimeMillis();
            log.debug("执行任务[{}]完成,用时: {} ms", task, (endTime - startTime));
        });
    }

}
